package com.yutel.phone.binh.service;

import java.util.ArrayList;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import com.yutel.phone.binh.data.DataQuery;

public abstract class SyncService extends IntentService {
	private static final String TAG = "SyncService";
	public static final String EXTRA_STATUS_RECEIVER = "cn.com.xinli.android.waka.extra.STATUS_RECEIVER";
	public static final int STATUS_RUNNING = 0x1;
	public static final int STATUS_ERROR = 0x2;
	public static final int STATUS_FINISHED = 0x100;

	protected DataQuery dq;

	public SyncService() {
		super(TAG);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		dq = new DataQuery(this);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Log.d(TAG, "onHandleIntent(intent=" + intent.toString() + ")");
		ResultReceiver receiver = intent
				.getParcelableExtra(EXTRA_STATUS_RECEIVER);
		if (receiver == null)
			return;
		else
			receiver.send(STATUS_RUNNING, Bundle.EMPTY);
		try {
			final long startLocal = System.currentTimeMillis();
			ArrayList<?> list = getData(intent);
			if (list != null) {
				final Bundle bundle = new Bundle();
				bundle.putSerializable(getKey(), list);
				bundle.putString(Intent.EXTRA_TEXT, getKey());
				receiver.send(STATUS_FINISHED, bundle);
			} else {
				final Bundle bundle = new Bundle();
				bundle.putString(Intent.EXTRA_TEXT, getKey());
				receiver.send(STATUS_ERROR, bundle);
			}
			Log.d(TAG, "local sync took "
					+ (System.currentTimeMillis() - startLocal) + "ms");
		} catch (Exception e) {
			Log.e(TAG, "Problem while syncing", e);
			final Bundle bundle = new Bundle();
			bundle.putString(Intent.EXTRA_TEXT, e.getMessage().toString());
			receiver.send(STATUS_ERROR, bundle);
		}
	}

	protected abstract ArrayList<?> getData(Intent intent);

	protected abstract String getKey();
}
